import React, {Component} from "react";
import { Button, Modal, Form, Input, Radio, Cascader, message, Select  } from 'antd';
import Pop from './Pop'
import Dialog from './Dialog'
import {connect} from 'dva';
import AddSelect from '@/components/AddSelect';
import Popop from './Popop';
import styles from './AddWarehouse.less';
import AddressNew from '@/components/AddressNewXian';
import { SelectAirport } from './SelectAirportModal';

const { Option } = Select;

const FormItem = Form.Item;

@connect(({cooperativeStore})=>({
  list: cooperativeStore.list,
}))
class CollectionCreateForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      cooper:{},
      regionVisible: false,//
      msgg:'',
      warehouseAddressArr:[],
      countryArr:[],
      addModalDisplay: 'none',
      address: '',
      modalVisible: true, // XIAN,
      showCellPhone: true
    }
  }

  // 提交表单
  handleSubmit = () => {
    let userInfo = this.props.form.getFieldsValue();  // 获取表单的值
    console.log('Form_Value', userInfo) // 打印表单的值
    const aaa = userInfo.addressInfo[0].name + '-' + userInfo.addressInfo[1].name + '-' + userInfo.addressInfo[2].name; // 改变地址数组转换为字符串
    console.log("userInfo_仓库地址：", aaa)
    userInfo["userId"] = 1  // 测试userId
    // this.state.warehouseAddressArr = userInfo.warehouseAddress
    // console.log("this.state.warehouseAddressArr",this.state.warehouseAddressArr)
    const { dispatch } = this.props;  // 发送表单的请求
    dispatch({
      type:'cooperativeStore/spsWareHouseInsert',
      payload:{
        data:{
          "name": userInfo.name,  //仓库名称
          "warehouseAddress": aaa,//仓库地址
          "detailedAddress": userInfo.address,  //详细地址
          "airportAddress": userInfo.airportAddress,  //对应机场
          "goodsType": '1,2',  //货物类型
          "contactName": userInfo.contactName,  //业务联系人
          "contactNumber": userInfo.contactNumber,  //联系人电话
          "userId": userInfo.userId,
          "creator": '' // 创建人 可以为空
        }
      }
    })

    // 表单的验证规则
    // this.props.form.validateFields((err, values)=>{
    //   console.log('values', values)
    //   if(!err){
    //     const { dispatch } = this.props;
    //     dispatch({
    //       type:'cooperativeStore/spsWareHouseInsert',
    //       payload:{
    //         data:{
    //           "name": values.name,
    //           "warehouseAddress": aaa,//values.warehouseAddress ,//this.state.msgg,
    //           "detailedAddress": values.detailedAddress,
    //           "airportAddress": values.airportAddress,
    //           "goodsType": values.goodsType,
    //           "contactName": values.contactName,
    //           "contactNumber": values.contactNumber,
    //           "userId": 1,
    //           "creator": ''
    //         }
    //       }
    //     })
    //     // history.go(0)
    //     message.success(`${values.name}添加成功`)
    //   }
    // })  
  };

  onCancel = () => {
    this.setState({ visible: false })
    console.log('concancel')
  }

  getAddress = (result, msg) => {
    this.state.address = msg
  }

  // XIAN
  handleModalVisible = () => {
    this.setState({
      modalVisible: false
    })
  }

  checkAddress = (rule, _value, callback) => {
    if (_value === undefined) {
      return callback('请选择地址');
    }
    const { addressType } = this.props;
    let value = _value[_value.length - 1].level;

    if (!value)
      return callback(
        '请选择地址'
      );
    if (_value[0].groupCode == 0) {
      if (addressType === TRANSPORT_TYPE.AIR) {
        if (value !== 3) {
          callback('请选择完整的地址信息');
        }
      } else {
        if (value !== 4) {
          callback('请选择完整的地址信息');
        }
      }
    } else {
      if (value !== 2) {
        callback('请选择完整的地址信息');
      }
    }
    callback();
  };

  showAirportModal = () => {
    this.setState({
      showCellPhone: true
    })
  }

  render() {
    const { visible, onCancel, onCreate, form} = this.props;
    const {regionVisible,countryArr}=this.state;
    const { getFieldDecorator } = form;
    const formItemLayout ={
      labelCol:{
        xs:24,
        sm:8
      },
      wrapperCol:{
        xs:24,
        sm:12
      }
    }
    //----------------
    function onChange(value, selectedOptions) {
      console.log("value-----------:选择地区：",value, selectedOptions);
    }
    
    function filter(inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }
    //---------------

    return (
      <Modal
        visible={visible}
        title="新增仓库"
        okText="保存"
        onCancel={onCancel}
        onOk={this.handleSubmit}
      >
        
        <Form layout={"horizontal"} onSubmit={this.handleSubmit}> 

          {/* 仓库名称 */}
          <FormItem label="仓库名称" {...formItemLayout}>
            {
              getFieldDecorator('name', {
                initialValue:"",
                rules: [{ required: true, message: '请填写仓库名称!' }],
            })(<Input />)}
          </FormItem>

          {/* 仓库地址 */}
          <FormItem
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            label="仓库地址"{...formItemLayout}
          >
            {form.getFieldDecorator('addressInfo', {
              initialValue:"",
              rules: [{ 
                required: true, 
                validator: this.checkAddress
              }],
              // validateTrigger: 'submit',
            })(<AddressNew addressType="2" type={1} maxLevel={4}/>)}
          </FormItem>

          {/* 详细地址 */}
          <FormItem labelCol={{ span: 4 }} wrapperCol={{ offset: 4, span: 18 }} label="详细地址"{...formItemLayout}>
            {form.getFieldDecorator('address', {
              rules: [
                {
                  required: true,
                  message: '请输入详细地址',
                },
                {
                  max: 200,
                  message: '最多30位',
                },
                {
                  pattern: /(?!\d+$)[\S]+/,
                  message: '请输入中英文和空格',
                },
              ],
            })(<Input />)}
          </FormItem>

          {/* 对应机场 */}
          <FormItem label="对应机场"{...formItemLayout}>
            {getFieldDecorator('airportAddress', {
              initialValue:"",
                rules: [{ required: true, message: '请填写对应机场!' }],
            })(<Input />)}
          </FormItem>

          {/* 货物类型 */}
          <FormItem label="货物类型"{...formItemLayout}>
            {
              getFieldDecorator('goodsType', {
                initialValue: [],
                rules: [{ required: true, message: '请填写货物类型!' }],
            })(<AirportShow showAirportModal={this.showAirportModal}/>
            )}
          </FormItem>
          
          <Pop />

          {/* 业务联系人 */}
          <FormItem label="业务联系人"{...formItemLayout}>
            {getFieldDecorator('contactName', {
              initialValue:"",
                rules: [{ required: true, message: '请填写联系人!' }],
            })(<Input />)}
          </FormItem>

          {/* 联系电话 */}
          <FormItem label="联系电话"{...formItemLayout}>
            {getFieldDecorator('contactNumber', {
              initialValue:"",
                rules: [{ required: true, message: '请填写联系电话!' }],
            })(<Input />)}
          </FormItem>

        </Form>
      </Modal>
    );
  }
}

export default Form.create()(CollectionCreateForm);

/**
 *  机场展示组件
 */
@connect(({shopaccount})=>({
  airportFormValue: shopaccount.airportFormValue,
}))
class AirportShow extends Component{
  render(){
      const { airportFormValue: list } = this.props
      return (
          <div onClick={this.props.showAirportModal} style={{width: '100%',flexWrap: 'wrap', minHeight: '32px',marginTop: '4px', border: '1px solid #d9d9d9',color: '#333',borderRadius: '4px',cursor: 'pointer', padding: '4px 11px 0',display: 'flex'}}>
              {
                list && list.map(item=>(
                    <span key={item.key} style={{
                        display: 'inline-block', 
                        padding: '0 5px',
                        backgroundColor: '#f6f8fa',
                        border: '1px solid #d9d9d9',
                        height: '24px',
                        lineHeight: '24px',
                        fontSize: '12px',
                        borderRadius: '3px',
                        marginRight: '5px',
                        marginBottom: '4px'

                        }}
                    >{item.abbrev}</span>
                ))
              }
          </div>
      )
  }
}

